package com.parking.status.sync.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.ByteOrder;

/**
 * Created by Administrator on 2015/9/18.
 */
public class RequestFinalEncoder extends MessageToByteEncoder<ByteBuf> {


    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {

        int length = msg.readableBytes();

        if (length < 0) {
            throw new IllegalArgumentException(
                    "Adjusted frame length (" + length + ") is less than zero");
        }

        //写长度
        out.order(ByteOrder.LITTLE_ENDIAN).writeInt(length);

        //先写不压缩，遇到要压缩的情况再加handler
        out.writeByte(0x00);
        //写内容
        out.writeBytes(msg, msg.readerIndex(), msg.readableBytes());

//        //FOR TEST WATCH
//        byte[] s = Unpooled.copiedBuffer(out).array();
    }
}